class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int allen = nums1.length+nums2.length;
        double mid = 0;
        if(1 == allen%2) {
            //allen/2+1 是第k个数
            mid = fun(nums1,nums2,allen/2+1);
            return mid;
        }else {
            mid = (fun(nums1,nums2,allen/2) + fun(nums1,nums2,allen/2+1))/2.0;
            return mid;
        }
    }
    public int fun(int[] num1,int[] num2,int k) {
        int len1 = num1.length;
        int len2 = num2.length;
        int index1 = 0,index2 = 0;
        while(true) {
            if(index1 == len1) {
                return num2[index2+k-1];
            }
            if(index2 == len2) {
                return num1[index1+k-1];
            }
            if(1 == k) {
                return Math.min(num1[index1],num2[index2]);
            }
            int mid = k/2 - 1;
            int newindex1 = Math.min(index1+mid,len1 - 1);
            int newindex2 = Math.min(index2+mid,len2 - 1) ;
            if(num1[newindex1]<=num2[newindex2]) {
                k -= (newindex1-index1+1);
                index1 = newindex1+1;
            }else {
                k -= (newindex2-index2+1);
                index2 = newindex2+1;
            }
            //为什么不能这么写：因为可能k前进的不是mid，因为可能有数组不够长，前进的是len-1，写成
            //写成(newindex-index)就解决了数组不够长的问题
           // k -= mid+1;
        }
    }
}